<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		#div1{width: 200px; height: 100px; background-color: red;position: absolute; text-align: center; color: #fff; font-weight: bold;}
	</style>
	<script type="text/javascript">
	window.onload = function (){
		var oDiv = document.getElementById('div1');
		lastX = 0;
		lastY = 0;
		
		oDiv.onmousedown = function (ev){
			var ev = ev || event;

			var disX = ev.clientX - this.offsetLeft;
			var disY = ev.clientY - this.offsetTop;

			document.onmousemove = function (ev){
				var ev = ev || event;

				var L = ev.clientX - disX;
				var T = ev.clientY - disY;

				oDiv.style.left = L + 'px';
				oDiv.style.top = T + 'px';

				iSpeedX = L - lastX;
				iSpeedY = T - lastY;

				lastX = L;
				lastY = T;

			}

			document.onmouseup = function (){
				document.onmousemove = document.onmouseup = null;

				doMove(oDiv);
			}
		}
		
	}

	var lastSpeedY = 0; 

	function doMove(obj){
		var xMax = document.documentElement.clientWidth - obj.offsetWidth;
		var yMax = document.documentElement.clientHeight - obj.offsetHeight;

		clearInterval(obj.timer);
		obj.timer = setInterval(function (){
			iSpeedY += 4;

			var x = obj.offsetLeft + iSpeedX;
			var y = obj.offsetTop + iSpeedY;

			if (x > xMax) {
				iSpeedX *= -0.8;
				x = xMax;
			} else if(x < 0){
				iSpeedX *= -0.8;
				x = 0;
			};

			if (y > yMax) {
				iSpeedY *= -0.8;
				iSpeedX *= 0.8;
				y = yMax;
			} else if(y < 0){
				iSpeedY *= -0.8;
				y = 0;
			};

			obj.style.left = x + 'px';
			obj.style.top = y + 'px';

			//检测停止
			if (Math.abs(iSpeedY - lastSpeedY) < 0.5 && Math.abs(iSpeedX) < 1) {
				clearInterval(obj.timer)
			};

			lastSpeedY = iSpeedY;			//判断完是否停止再在最后更新赋值

			//测试用
			obj.innerHTML = 'x:'+ iSpeedX +'<br>y:'+ iSpeedY+'<br>L:'+ obj.offsetLeft+'<br>T:'+ obj.offsetTop;
		},30);
	}
	</script>
</head>
<body>
	<div id="div1">拖拽我</div>
</body>
</html>